package com.hzw.net.page.status

import android.content.Context
import android.view.View
import android.view.ViewStub
import android.widget.Button
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.hzw.core.view.click
import com.hzw.net.R
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout

class AbnormalPageStatus(
    override val context: Context,
    override var isEnableRefresh: Boolean = true,
    private val iconResId: Int = 0,
    private val text: String = "",
    private val retryText: String? = null,
    private val refresh: ((refreshLayout: RefreshLayout) -> Unit)? = null,
    private val retry: (() -> Unit)? = null
) : IAbnormalStatus {

    private lateinit var view: View

    override val viewStub: ViewStub = ViewStub(context, R.layout.layout_state_view_stub)

    private lateinit var iconView: ImageView
    private lateinit var textView: TextView
    private lateinit var retryBtn: Button

    override fun onRefresh(refreshLayout: RefreshLayout) {
        refresh?.invoke(refreshLayout)
    }

    override fun onRetry() {
        retry?.invoke()
    }

    override fun inflate(): View {
        view = viewStub.inflate()
        val container = view.findViewById<FrameLayout>(R.id.pageContainer)
        val realView = View.inflate(context, R.layout.layout_abnormal, null)
        container.removeAllViews()
        container.addView(realView)
        return view
    }


    override fun initView() {
        val smartRefreshLayout = view as SmartRefreshLayout
        smartRefreshLayout.setEnableRefresh(isEnableRefresh)
        if (isEnableRefresh) {
            smartRefreshLayout.setOnRefreshListener {
                onRefresh(it)
            }
        }
        iconView = view.findViewById(R.id.iconView)
        textView = view.findViewById(R.id.textView)
        retryBtn = view.findViewById(R.id.retryBtn)

        retryBtn.click {
            onRetry()
        }
        changeView(iconResId, text, retryText)
    }

    override fun changeView(iconResId: Int, text: String, retryText: String?) {
        if (iconResId != 0) {
            iconView.setImageResource(iconResId)
        }
        if (text.isNotBlank()) {
            textView.text = text
        }

        if (!retryText.isNullOrBlank()) {
            retryBtn.text = retryText
        }
    }

    override fun release() {

    }
}